package todo;

import se.lth.cs.realtime.PeriodicThread;
import se.lth.cs.realtime.RTThread;
import done.AbstractWashingMachine;

public class TemperatureController extends PeriodicThread {
	
	private AbstractWashingMachine machine;
	private TemperatureEvent last_event;
	private boolean stable;

	public TemperatureController(AbstractWashingMachine machine) {
		super(Sim.time(1000));
		this.machine = machine;
	}
	
	public void perform() {
		while (!mailbox.isEmpty()) {
			last_event = (TemperatureEvent)mailbox.tryFetch();
		}
		if (last_event == null) return;
		
		switch (last_event.getMode()) {
		case (TemperatureEvent.TEMP_IDLE):
			machine.setHeating(false);
			break;
			
		case (TemperatureEvent.TEMP_SET):
			if (machine.getTemperature() < last_event.getTemperature()-1.9) {
				machine.setHeating(true);
			} else if (machine.getTemperature() > last_event.getTemperature()-0.1) {
				machine.setHeating(false);
				if (!stable) {
					stable=true;
					((RTThread)last_event.getSource()).putEvent(new AckEvent(this));
				}
			}
		}
	}
}
